<template>
    <div>
        <!-- 标题部分 -->
        <div class="Header">
            <el-select v-model="addTest.startRange" placeholder="请选择起始范围">
                <el-option v-for="(item,index) in chapters" :key="'select-'+index"
                    :label="item.chapterNumber+item.description" :value="item.id"></el-option>
            </el-select>
            <el-input placeholder="请输入标题" v-model="addTest.title">
            </el-input>
            <el-select v-model="addTest.endRange" placeholder="请选择截至范围">
                <el-option v-for="(item,index) in chapters" :key="'select_end'+index"
                    :label="item.chapterNumber+item.description" :value="item.id"></el-option>
            </el-select>
        </div>
        <div style="display: flex; justify-content: right; margin-right: 50px; margin-bottom: 5px;">
            <el-button type="primary" plain @click="produceTest()">生成试卷</el-button>
        </div>

        <!-- 第一部分 -->
        <div class="selectQuestion">
            <!-- 选择题+判断题 -->
            <div class="selectQuestion_1">
                <!-- 选择题选择 -->
                <div>
                    <span>选择题选择：</span>
                    <el-autocomplete v-model="chooseQuestionNumberState"
                        :fetch-suggestions="chooseQuestionNumberSearchAsync" placeholder="请选择题目编号"
                        @select="handleChooseQuestionSelect"></el-autocomplete>
                    <span>分值：</span>
                    <el-input-number v-model="addTest.chooseScore"></el-input-number>
                </div>
                <!-- 判断题选择 -->
                <div>
                    <span>判断题选择：</span>
                    <el-autocomplete v-model="judgeQuestionNumberState"
                        :fetch-suggestions="judgeQuestionNumberSearchAsync" placeholder="请选择题目编号"
                        @select="handlejudgeQuestionSelect"></el-autocomplete>
                    <span>分值：</span>
                    <el-input-number v-model="addTest.judgeScore"></el-input-number>
                </div>
            </div>
            <!-- 填空+编程 -->
            <div class="selectQuestion_2">
                <!-- 填空题选择 -->
                <div>
                    <span>填空题选择：</span>
                    <el-autocomplete v-model="fillEmptyQuestionNumberState"
                        :fetch-suggestions="fillEmptyQuestionNumberSearchAsync" placeholder="请选择题目编号"
                        @select="handlefillEmptyQuestionSelect"></el-autocomplete>
                </div>
                <!-- 编程题选择 -->
                <div>
                    <span>编程题选择：</span>
                    <el-autocomplete v-model="encodeQuestionNumberState"
                        :fetch-suggestions="encodeQuestionNumberSearchAsync" placeholder="请选择题目编号"
                        @select="handleencodeQuestionSelect"></el-autocomplete>
                </div>
            </div>
        </div>

        <!-- 第二部分， 展示选择了哪些题目 -->
        <div class="qusetion_preview">
            <!-- 标题预览 -->
            <h3>{{addTest.title}}</h3>
            <!-- 选择题预览 -->
            <span v-if="chooseQuestionToView.length>0" class="samll_title">一、选择题部分:
                [共{{addTest.chooseScore*chooseQuestionToView.length}}分]</span>
            <div class="choose_judge_preview" v-for="(item, index) in chooseQuestionToView" :key="'choose'+index">
                <p>({{ index+1 }})<el-tag>{{ item.questionNumber }}</el-tag>[{{ addTest.chooseScore+'分' }}]&nbsp;
                    {{ item.description }}<span style="font-size: 26px; color: red;">({{ item.answer }})</span></p>
                <div class="tagTwo_button">
                    <el-tag>{{ item.questionNumber }}</el-tag>
                    <el-tag type="success">第{{ item.chapter }}章</el-tag>
                    <el-button type="danger" size="mini" @click="delectChooseQuestion(item.id)">删除题目</el-button>
                </div>
                <ul>
                    <li>A. {{item.optionA}}</li>
                    <li>B. {{item.optionB}}</li>
                    <li>C. {{item.optionC}}</li>
                    <li>D. {{item.optionD}}</li>
                </ul>
            </div>

            <!-- 判断题预览 -->
            <span v-if="judgeQuestionToView.length>0" class="samll_title">二、判断题部分:
                [共{{addTest.judgeScore*judgeQuestionToView.length}}分]</span>
            <div v-for="(item,index) in judgeQuestionToView" :key="'judge'+index">
                <p>({{ index+1 }})<el-tag>{{ item.questionNumber }}</el-tag>[{{ addTest.judgeScore+'分' }}]&nbsp;
                    {{ item.description }} <span style="font-size: 26px; color: red;">({{ item.answer === 1?'正确':'错误'
                        }})</span></p>
                <div class="tagTwo_button">
                    <el-tag>{{ item.questionNumber }}</el-tag>
                    <el-tag type="success">第{{ item.chapter }}章</el-tag>
                    <el-button type="danger" size="mini" @click="delectjudgeQuestion(item.id)">删除题目</el-button>
                </div>
            </div>

            <!-- 填空题预览 -->
            <span v-if="fillEmptyQuestionToView.length>0" class="samll_title">三、程序填空题部分:</span>
            <div v-for="(item,index) in fillEmptyQuestionToView" :key="'fillEmpty'+index">
                <p class="fillEmpty_code_p">({{ index+1 }})<el-tag>{{ item.questionNumber }}</el-tag>&nbsp;{{
                    item.description }} [{{addTest.fillEmpty.find(k=>k.id===item.id).scoresview}}分]</p>
                <div class="fillEmpty_code_answer">
                    <!-- 代码区域 -->
                    <div>
                        <pre><code>{{ item.code }}</code></pre>
                    </div>
                    <!-- 答案区域 -->
                    <div class="fill_answer">
                        <!-- 第一行 标签 -->
                        <div class="fill_empty_tagTwo_button">
                            <el-tag>{{ item.questionNumber }}</el-tag>
                            <el-tag type="success">第{{ item.chapter }}章</el-tag>
                            <el-button type="danger" size="mini"
                                @click="delectFillEmptyQuestion(item.id)">删除题目</el-button>
                        </div>
                        <!-- 第二步，遍历答案，每个答案设置分值 -->
                        <div>
                            <ul>
                                <li v-for="(item_a,index_a) in item.answers" :key="'fillemptyanswer'+index_a"
                                    class="answer_score">
                                    <span>{{item_a.order}}:{{item_a.answer}}</span>
                                    <el-input size="small"
                                        v-model.number="addTest.fillEmpty.find(a=>a.id===item.id).scores.find(b=>b.order===item_a.order).score">
                                        <template slot="prepend">分值：</template>
                                    </el-input>
                                </li>
                            </ul>
                        </div>

                    </div>

                </div>
            </div>

            <!-- 编程题预览 -->
            <span v-if="encodeQuestionToView.length>0" class="samll_title">四、编程题部分:</span>
            <div v-for="(item,index) in encodeQuestionToView" :key="'encode'+index">
                <div style="display: flex; justify-content: space-between">
                    <span>({{ index+1 }})<el-tag>{{ item.questionNumber }}</el-tag>{{ item.title }}
                    </span>
                    <div class="tagTwo_button">
                        <el-tag>{{ item.questionNumber }}</el-tag>
                        <el-tag type="success">第{{ item.chapter }}章</el-tag>
                        <el-input style="width: 200px;" v-model.number="addTest.encode.find(a=>a.id===item.id).score">
                            <template slot="prepend">分值：</template>
                        </el-input>
                        <el-button type="danger" size="mini" @click="delectEncodeQuestion(item.id)">删除题目</el-button>
                    </div>
                </div>
                <p>{{ item.description }}</br>{{item.suggest}}</p>
            </div>
        </div>

        <!-- 第三部分， 提交题目 -->
        <div style="text-align: center; border-top:2px #000 solid ; padding-top: 10px;"
            v-if="addTest.choose.length!=0||addTest.judge.length!=0||addTest.fillEmpty.length!=0||addTest.encode.length!=0">
            <el-button type="success" @click="submitTest">提交</el-button>
        </div>

        <el-dialog title="发布测试" :visible.sync="TestdialogVisible" width="40%" :before-close="handleClose">
            <ul>
                <li>选择题部分：共{{addTest.choose.length}}道，{{addTest.chooseScore}}分。共{{addTest.choose.length*addTest.chooseScore}}分
                </li>
                <li>判断题部分：共{{addTest.judge.length}}道，{{addTest.judgeScore}}分。共{{addTest.judge.length*addTest.judgeScore}}分
                </li>
                <li>程序填空题：共{{addTest.fillEmpty.length}}道，共{{filltotalscole}}分</li>
                <li>编程题部分：共{{addTest.encode.length}}道，共{{encodetotalscole}}分</li>
                <li>总分：{{totalscole}}</li>
            </ul>
            <!-- 起始时间和结束时间选择 -->
            <span>开始时间: </span>
            <el-date-picker class="date-picker" v-model="addTest.startTime" type="datetime" placeholder="选择开始时间">
            </el-date-picker><br>
            <p></p>
            <span>结束时间: </span>
            <el-date-picker class="date-picker" v-model="addTest.endTime" type="datetime" placeholder="选择结束时间">
            </el-date-picker><br>
            <p></p>
            <span>班级选择: </span>
            <!-- 班级选择 -->
            <el-select v-model="addTest.classes" multiple placeholder="请选择班级">
                <el-option v-for="item in classes" :key="item.id" :label="item.className" :value="item.id">
                </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addTestTo">确 定</el-button>
            </span>
        </el-dialog>


        <!-- 生成试卷弹框 -->
        <el-dialog title="随机生成试卷" :visible.sync="generate_dialogVisible" width="50%"
            :before-close="generate_handleClose">

            <div class="generate">
                <el-input @input="handleInputChoose" placeholder="请输入选择题个数" v-model="generate.chooseNumber"
                    class="generate_first">
                    <template slot="prepend" class="generate.two">选择题个数:</template>
                    <template slot="append"
                        class="generate_three">{{chooseQuestionNumberTouUsed.length}}个选择题可以使用</template>
                </el-input>
                <el-input @input="handleInputJudge" placeholder="请输入判断题个数" v-model="generate.judgeNumber"
                    class="generate_first">
                    <template slot="prepend" class="generate.two">判断题个数:</template>
                    <template slot="append"
                        class="generate_three">{{judgeQuestionNumberTouUsed.length}}个判断题可以使用</template>
                </el-input>
                <el-input @input="handleInputFill" placeholder="请输入填空题个数" v-model="generate.fillEmptyNumber"
                    class="generate_first">
                    <template slot="prepend" class="generate.two">填空题个数:</template>
                    <template slot="append"
                        class="generate_three">{{fillEmptyQuestionNumberTouUsed.length}}个填空题可以使用</template>
                </el-input>
                <el-input @input="handleInputEncode" placeholder="请输入编程题个数" v-model="generate.encodeNumber"
                    class="generate_first">
                    <template slot="prepend" class="generate.two">编程题个数:</template>
                    <template slot="append"
                        class="generate_three">{{encodeQuestionNumberTouUsed.length}}个编程题可以使用</template>
                </el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="generate_dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="generate_to_random()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
    export default {
        watch: {
            'addTest.endRange': { // 结束章节id 属性变化，必须大于等于开始章节id 
                handler(newVal, oldVal) {
                    if (this.addTest.startRange != null) {
                        if (this.addTest.startRange > newVal) {
                            if (oldVal != null) {
                                this.addTest.endRange = oldVal
                            } else {
                                this.addTest.endRange = this.addTest.startRange
                            }
                            return this.$message("注意范围别搞反了")
                        }
                        this.getQuestionNumber()
                    }
                },
            },
            'addTest.startRange': { // 结束章节id 属性变化，必须大于等于开始章节id 
                handler(newVal, oldVal) {
                    if (this.addTest.endRange != null) {
                        if (this.addTest.endRange < newVal) {
                            if (oldVal != null) {
                                this.addTest.startRange = oldVal
                            } else {
                                this.addTest.startRange = this.addTest.endRange
                            }
                            return this.$message("注意范围别搞反了")
                        }
                        this.getQuestionNumber()
                    }
                },
            },
            'addTest.fillEmpty': {
                handler(newVal, oldVal) {
                    this.computeScores()
                },
                deep: true,
                immediate: true
            },
        },
        created() {
            this.getChapter()
        },
        data() {
            return {
                generate: {
                    chooseNumber: 0,
                    judgeNumber: 0,
                    fillEmptyNumber: 0,
                    encodeNumber: 0,
                },
                generate_dialogVisible: false,        //控制生成试卷的弹框
                chapters: null,                      // 章节数据
                // 试卷总参数
                addTest: {
                    title: "",                      // 试卷标题
                    judgeScore: 5,                  // 判断题分值
                    chooseScore: 5,                 // 选择题分值
                    choose: [],                     // 选择题
                    judge: [],                      // 判断题
                    fillEmpty: [],                  // 程序填空题
                    encode: [],                     // 编程题
                    workType: 1,                    // 测试种类，1表示系统评判
                    startRange: null,              // 开始范围
                    endRange: null,                // 结束范围
                    classes: [],                    // 班级选择
                    startTime: null,               // 开始时间
                    endTime: null,                 // 结束时间
                },
                // 班级信息
                classes: null,

                // 选择题编号
                chooseQuestionNumberTouUsed: [],
                chooseQuestionNumberState: '',
                // 用于展示添加了哪一些选择题
                chooseQuestionToView: [],
                // 判断题题编号
                judgeQuestionNumberTouUsed: [],
                judgeQuestionNumberState: '',
                // 用于展示添加了哪一些判断题
                judgeQuestionToView: [],
                // 程序填空题编号
                fillEmptyQuestionNumberTouUsed: [],
                fillEmptyQuestionNumberState: '',
                // 用于展示添加了哪一些填空题
                fillEmptyQuestionToView: [],
                // 编程题编号
                encodeQuestionNumberTouUsed: [],
                encodeQuestionNumberState: '',
                // 用于展示添加了哪一些编程题
                encodeQuestionToView: [],
                TestdialogVisible: false,
                filltotalscole: 0,
                encodetotalscole: 0,
                totalscole: 0
            };
        },
        methods: {
            // 时间格式转化
            formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1  
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');

                // 注意：这里返回的是本地时间的字符串，不是UTC时间的字符串  
                return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
            },
            // 获取班级信息
            async getCalssList() {
                const { data: res } = await this.$axios.get("/getClasses")
                this.classes = res.data
            },
            // 获取所有章节
            async getChapter() {
                const { data: res } = await this.$axios.get("/chapter/getChapter")
                this.chapters = res.data
            },
            // 赋值编号
            questionNumberToValue(array1, array2) {
                for (let i = 0; i < array2.length; i++) {
                    array1.push({ value: "", id: null })
                    array1[i].id = array2[i].id
                    array1[i].value = array2[i].questionNumber
                }
            },
            // 获取所有编号(带考试范围)
            async getQuestionNumber() {
                this.chooseQuestionNumberTouUsed = []
                this.judgeQuestionNumberTouUsed = []
                this.fillEmptyQuestionNumberTouUsed = []
                this.encodeQuestionNumberTouUsed = []
                const { data: res } = await this.$axios.get('/publishtest/getQuestionNumber', {
                    params: {
                        startRange: this.addTest.startRange,
                        endRange: this.addTest.endRange
                    }
                })
                if (res.code === 200) {
                    this.questionNumberToValue(this.chooseQuestionNumberTouUsed, res.data.chooseQuestionNumber)
                    this.questionNumberToValue(this.judgeQuestionNumberTouUsed, res.data.judgeQuestionNumber)
                    this.questionNumberToValue(this.fillEmptyQuestionNumberTouUsed, res.data.fillEmptyQuestionNumber)
                    this.questionNumberToValue(this.encodeQuestionNumberTouUsed, res.data.encodeQuestionNumber)
                } else {
                    return this.$message.error("网络错误")
                }
            },
            // 根据题目id和题目种类获取该题目数据
            async getQuestionById(id, questionType) {
                const { data: res } = await this.$axios.get('/publishtest/getQuestion', {
                    params: {
                        id: id,
                        questionType: questionType,
                    }
                })
                if (res.code === 200) {
                    // 根据这个questionType分配给四个题目展示数据
                    if (questionType === 1) {
                        this.chooseQuestionToView.push(res.data)
                    } else if (questionType === 2) {
                        this.judgeQuestionToView.push(res.data)
                    } else if (questionType === 3) {
                        // 程序填空题
                        this.fillEmptyQuestionToView.push(res.data)
                        var answers = this.fillEmptyQuestionToView.find(item => item.id === id).answers
                        for (let i = 0; i < answers.length; i++) {
                            this.addTest.fillEmpty.find(item => item.id === id).scores.push({ order: answers[i].order, score: 0 })
                        }
                    } else if (questionType === 4) {
                        this.encodeQuestionToView.push(res.data)
                    }
                } else {
                    return this.$message.error("网络错误")
                }
            },

            // 选择题远程搜索
            chooseQuestionNumberSearchAsync(queryString, cb) {
                var results = queryString ? this.chooseQuestionNumberTouUsed.filter(this.createStateFilter(queryString)) : this.chooseQuestionNumberTouUsed;
                cb(results)
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            handleChooseQuestionSelect(item) {
                this.chooseQuestionNumberState = null
                for (let i = 0; i < this.addTest.choose.length; i++) {
                    if (item.id === this.addTest.choose[i]) {
                        return this.$message("该题目以及存在了")
                    }
                }
                this.addTest.choose.push(item.id)
                // 根据id，从后端获取该题目数据
                this.getQuestionById(item.id, 1)
            },
            // 删除选择题
            delectChooseQuestion(id) {
                this.addTest.choose = this.addTest.choose.filter(item => item != id)
                this.chooseQuestionToView = this.chooseQuestionToView.filter(item => item.id != id)
            },

            // 判断题远程搜索
            judgeQuestionNumberSearchAsync(queryString, cb) {
                var results = queryString ? this.judgeQuestionNumberTouUsed.filter(this.createStateFilter(queryString)) : this.judgeQuestionNumberTouUsed;
                cb(results)
            },
            handlejudgeQuestionSelect(item) {
                this.judgeQuestionNumberState = null
                for (let i = 0; i < this.addTest.judge.length; i++) {
                    if (item.id === this.addTest.judge[i]) {
                        return this.$message("该题目以及存在了")
                    }
                }
                this.addTest.judge.push(item.id)
                // 根据id，从后端获取该题目数据
                this.getQuestionById(item.id, 2)
            },
            // 删除判断题
            delectjudgeQuestion(id) {
                this.addTest.judge = this.addTest.judge.filter(item => item != id)
                this.judgeQuestionToView = this.judgeQuestionToView.filter(item => item.id != id)
            },

            // 程序填空题远程搜索
            fillEmptyQuestionNumberSearchAsync(queryString, cb) {
                var results = queryString ? this.fillEmptyQuestionNumberTouUsed.filter(this.createStateFilter(queryString)) : this.fillEmptyQuestionNumberTouUsed;
                cb(results)
            },
            handlefillEmptyQuestionSelect(item) {
                this.fillEmptyQuestionNumberState = null
                for (let i = 0; i < this.addTest.fillEmpty.length; i++) {
                    if (item.id === this.addTest.fillEmpty[i].id) {
                        return this.$message("该题目以及存在了")
                    }
                }
                this.addTest.fillEmpty.push({ id: item.id, scores: [], scoresview: null })
                // 根据id，从后端获取该题目数据
                this.getQuestionById(item.id, 3)
            },
            // 删除填空题
            delectFillEmptyQuestion(id) {
                this.addTest.fillEmpty = this.addTest.fillEmpty.filter(item => item.id != id)
                this.fillEmptyQuestionToView = this.fillEmptyQuestionToView.filter(item => item.id != id)
            },
            // 根据填空题补充填空题的总分
            computeScores() {
                for (let i = 0; i < this.addTest.fillEmpty.length; i++) {
                    var s = 0;
                    for (let j = 0; j < this.addTest.fillEmpty[i].scores.length; j++) {
                        s = s + Number(this.addTest.fillEmpty[i].scores[j].score)
                    }
                    this.addTest.fillEmpty[i].scoresview = s
                }
            },

            // 编程题远程搜索
            encodeQuestionNumberSearchAsync(queryString, cb) {
                var results = queryString ? this.encodeQuestionNumberTouUsed.filter(this.createStateFilter(queryString)) : this.encodeQuestionNumberTouUsed;
                cb(results)
            },
            handleencodeQuestionSelect(item) {
                this.encodeQuestionNumberState = null
                for (let i = 0; i < this.addTest.encode.length; i++) {
                    if (item.id === this.addTest.encode.id) {
                        return this.$message("该题目以及存在了")
                    }
                }
                this.addTest.encode.push({ id: item.id, score: null })
                // 根据id，从后端获取该题目数据
                this.getQuestionById(item.id, 4)
            },
            // 删除编程题
            delectEncodeQuestion(id) {
                this.addTest.encode = this.addTest.encode.filter(item => item.id != id)
                this.encodeQuestionToView = this.encodeQuestionToView.filter(item => item.id != id)
            },

            // 提交测试题
            submitTest() {
                // 第一步，校验这个分值是否设置好
                if (this.addTest.chooseScore === 0 || this.addTest.judgeScore === 0) {
                    return this.$message("请设置选择判断分值")
                } else if (this.addTest.title === null || this.addTest.title === "") {
                    return this.$message("请输入标题")
                }
                for (let i = 0; i < this.addTest.fillEmpty.length; i++) {
                    for (let j = 0; j < this.addTest.fillEmpty[i].scores.length; j++) {
                        if (this.addTest.fillEmpty[i].scores[j].score === 0 || isNaN(Number(this.addTest.fillEmpty[i].scores[j].score))) {
                            return this.$message("请完善程序填空题分值")
                        }
                    }
                }
                for (let i = 0; i < this.addTest.encode.length; i++) {
                    if (this.addTest.encode[i].score === 0 || this.addTest.encode[i].score === null || isNaN(Number(this.addTest.encode[i].score))) {
                        return this.$message("请完善编程题分值")
                    }
                }
                // 第二部计算三个总分值
                this.getCalssList()
                var a = 0
                for (let i = 0; i < this.addTest.fillEmpty.length; i++) {
                    a = a + this.addTest.fillEmpty[i].scoresview
                }
                this.filltotalscole = a
                a = 0

                for (let i = 0; i < this.addTest.encode.length; i++) {
                    a = a + Number(this.addTest.encode[i].score)
                }
                this.encodetotalscole = a
                a = 0
                this.totalscole = this.addTest.choose.length * this.addTest.chooseScore
                    + this.addTest.judge.length * this.addTest.judgeScore
                    + this.filltotalscole + this.encodetotalscole
                this.TestdialogVisible = true
            },

            handleClose() {
                this.filltotalscole = 0
                this.encodetotalscole = 0
                this.totalscole = 0
                this.TestdialogVisible = false
                this.addTest.startTime = null
                this.addTest.endTime = null
                this.addTest.classes = []
            },

            async addTestTo() {
                if (this.addTest.startTime === null || this.addTest.endTime === null ||
                    this.addTest.classes.length === 0) {
                    return this.$message("请完善资料")
                }
                this.addTest.startTime = this.formatDate(this.addTest.startTime)
                this.addTest.endTime = this.formatDate(this.addTest.endTime)
                const { data: res } = await this.$axios.put('/publishtest/addTest', this.addTest)
                if (res.code === 303) {
                    return this.$message.error("时间格式不正确")
                }
                if (res.code === 200) {
                    this.handleClose()
                    return this.$message.success("发布成功")
                }
                return this.$message.error("网络错误")
            },


            // 随机生成试卷的弹窗打开口
            produceTest() {
                // 第一步，查询题目起始范围是否写好
                if (this.addTest.startRange === null || this.addTest.endRange === null) {
                    return this.$message("请先选择起始范围")
                }
                this.generate_dialogVisible = true
            },
            // 对话框关闭
            generate_handleClose() {
                this.generate = {
                    chooseNumber: 0,
                    judgeNumber: 0,
                    fillEmptyNumber: 0,
                    encodeNumber: 0,
                },
                    this.generate_dialogVisible = false
            },
            generate_to_random() {
                if(this.generate.chooseNumber===null){
                    return this.generate.chooseNumber===0
                }
                if(this.generate.judgeNumber===null){
                    return this.generate.judgeNumber===0
                }
                if(this.generate.fillEmptyNumber===null){
                    return this.generate.fillEmptyNumber===0
                }
                if(this.generate.encodeNumber===null){
                    return this.generate.encodeNumber===0
                }
                // 选择题
                let choose = this.getRandomElements(this.chooseQuestionNumberTouUsed, this.generate.chooseNumber)
                for (let i = 0; i < choose.length; i++) {
                    this.addTest.choose.push(choose[i].id)
                    this.getQuestionById(choose[i].id, 1)
                }
                // 判断题
                let judge = this.getRandomElements(this.judgeQuestionNumberTouUsed, this.generate.judgeNumber)
                for (let i = 0; i < judge.length; i++) {
                    this.addTest.judge.push(judge[i].id)
                    this.getQuestionById(judge[i].id, 2)
                }
                // 填空题
                let fillEmpty = this.getRandomElements(this.fillEmptyQuestionNumberTouUsed, this.generate.fillEmptyNumber)
                for (let i = 0; i < fillEmpty.length; i++) {
                    this.addTest.fillEmpty.push({ id: fillEmpty[i].id, scores: [], scoresview: null })
                    this.getQuestionById(fillEmpty[i].id, 3)
                }
                // 编程题
                let encode = this.getRandomElements(this.encodeQuestionNumberTouUsed, this.generate.encodeNumber)
                for (let i = 0; i < encode.length; i++) {
                    this.addTest.encode.push({ id: encode[i].id, score: null })
                    this.getQuestionById(encode[i].id, 4)
                }
                this.generate_handleClose()
                this.getQuestionNumber()
                return this.$message.success("生成试卷成功")
            },
            // 随机
            getRandomElements(arr, a) {
                // 创建一个新数组来存放结果  
                const result = [];
                // 确保a的值不会大于数组的长度  
                const maxLength = Math.min(a, arr.length);
                // 从数组中随机选择元素  
                for (let i = 0; i < maxLength; i++) {
                    // 生成一个随机索引  
                    const randomIndex = Math.floor(Math.random() * arr.length);
                    // 将选中的元素添加到结果数组中  
                    result.push(arr[randomIndex]);
                    // 从原数组中删除已选中的元素，避免重复选择  
                    arr.splice(randomIndex, 1);
                }
                // 返回包含随机元素的新数组  
                return result;
            },
            // 只能输入数字
            handleInputChoose(value) {
                // 使用正则表达式替换掉非数字字符  
                this.generate.chooseNumber= value.replace(/\D/g, '');
            },
            handleInputJudge(value) {
                // 使用正则表达式替换掉非数字字符  
                this.generate.judgeNumber= value.replace(/\D/g, '');
            },
            handleInputFill(value) {
                // 使用正则表达式替换掉非数字字符  
                this.generate.fillEmptyNumber= value.replace(/\D/g, '');
            },
            handleInputEncode(value) {
                // 使用正则表达式替换掉非数字字符  
                this.generate.encodeNumber= value.replace(/\D/g, '');
            },
        },
    }
</script>

<style lang="less" scoped>
    /* 标题部分 */
    .Header {
        display: flex;
        justify-content: center;

        .el-input {
            margin: auto 20px;
            width: 400px;
        }

        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 10px double #76aca9;
    }

    /* 题目选择部分 */
    .selectQuestion {
        .selectQuestion_1 {
            display: flex;
            justify-content: space-around;
        }

        .selectQuestion_2 {
            div {
                padding-right: 115px;
            }

            margin-top: 5px;
            display: flex;
            justify-content: space-around;
            padding-bottom: 10px;
            border-bottom: 3px solid #000;
        }
    }

    /* 题目预览样式 */
    /* 小标题样式 */
    .samll_title {
        font-size: 20px;
    }

    /* 第三栏目 */
    .qusetion_preview {
        margin-left: 30px;

        /* 标签， 四个题目的公共部分 */
        .tagTwo_button {
            text-align: end;
            margin-right: 50px;

            .el-tag {
                margin: 0 20px;
            }

            .el-button {
                margin-left: 30px;
            }
        }

        /* 程序填空题其他部分 */
        .fillEmpty_code_p {
            margin: 5px 0;
            padding: 0;
        }

        .fillEmpty_code_answer {

            display: flex;
            justify-content: space-between;
            margin: 0;
            padding: 0;

            /* 代码区域 */
            pre {
                margin-top: 0;
                width: 700px;
                background-color: #f2f2f2;
                margin-left: 15px;
                font-size: 16px;
                line-height: 16px;
                margin-bottom: 0;
                padding-bottom: 10px;
            }

            /* 答案区域 */
            .fill_answer {
                width: 400px;
                background-color: #f2f2f2;

                /* 第一行标签 */
                .fill_empty_tagTwo_button {
                    margin-top: 5px;
                    display: flex;
                    justify-content: space-around;
                }

                /* 答案赋分区域 */
                .answer_score {
                    margin-bottom: 10px;
                    display: flex;
                    justify-content: space-between;
                    padding-right: 25px;

                    .el-input {
                        width: 150px;
                    }
                }
            }
        }

        h3 {
            margin: 20px 0;
            text-align: center;
            padding: 0;
            font-size: 22px;
        }

        /* 选择题 判断题样式 */
        .choose_judge_preview {
            margin: 10px 0;

            ul {
                margin-top: 0;
            }
        }
    }

    /* 对话框*/
    .el-dialog {
        ul {
            li {
                margin-bottom: 10px;
                font-size: 16px;
            }
        }

        .el-date-picker {
            margin-bottom: 40px;
        }

        .el-select {
            width: 70%;
        }
    }

    /* 生产试卷 */
    .generate {
        .generate_first {
            margin-bottom: 10px;
        }

        .generate_two {
            width: 100px;
        }

        .generate_three {
            width: 250px;
        }
    }
</style>